"use strict";

function _toConsumableArray(t) {
  return _arrayWithoutHoles(t) || _iterableToArray(t) || _unsupportedIterableToArray(t) || _nonIterableSpread()
}

function _nonIterableSpread() {
  throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")
}

function _unsupportedIterableToArray(t, e) {
  if (t) {
    if ("string" == typeof t) return _arrayLikeToArray(t, e);
    var r = Object.prototype.toString.call(t).slice(8, -1);
    return "Object" === r && t.constructor && (r = t.constructor.name), "Map" === r || "Set" === r ? Array.from(t) : "Arguments" === r || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r) ? _arrayLikeToArray(t, e) : void 0
  }
}

function _iterableToArray(t) {
  if ("undefined" != typeof Symbol && null != t[Symbol.iterator] || null != t["@@iterator"]) return Array.from(t)
}

function _arrayWithoutHoles(t) {
  if (Array.isArray(t)) return _arrayLikeToArray(t)
}

function _arrayLikeToArray(t, e) {
  (null == e || e > t.length) && (e = t.length);
  for (var r = 0, n = new Array(e); r < e; r++) n[r] = t[r];
  return n
}

function ownKeys(e, t) {
  var r = Object.keys(e);
  if (Object.getOwnPropertySymbols) {
    var n = Object.getOwnPropertySymbols(e);
    t && (n = n.filter(function (t) {
      return Object.getOwnPropertyDescriptor(e, t).enumerable
    })), r.push.apply(r, n)
  }
  return r
}

function _objectSpread(e) {
  for (var t = 1; t < arguments.length; t++) {
    var r = null != arguments[t] ? arguments[t] : {};
    t % 2 ? ownKeys(Object(r), !0).forEach(function (t) {
      _defineProperty(e, t, r[t])
    }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(r)) : ownKeys(Object(r)).forEach(function (t) {
      Object.defineProperty(e, t, Object.getOwnPropertyDescriptor(r, t))
    })
  }
  return e
}

function _defineProperty(t, e, r) {
  return e in t ? Object.defineProperty(t, e, {
    value: r,
    enumerable: !0,
    configurable: !0,
    writable: !0
  }) : t[e] = r, t
}

function _classCallCheck(t, e) {
  if (!(t instanceof e)) throw new TypeError("Cannot call a class as a function")
}

function _defineProperties(t, e) {
  for (var r = 0; r < e.length; r++) {
    var n = e[r];
    n.enumerable = n.enumerable || !1, n.configurable = !0, "value" in n && (n.writable = !0), Object.defineProperty(t, n.key, n)
  }
}

function _createClass(t, e, r) {
  return e && _defineProperties(t.prototype, e), r && _defineProperties(t, r), t
}
var SYS_INFO = wx.getSystemInfoSync(),
  WxCanvas2d = function () {
    function t() {
      _classCallCheck(this, t), this.query = null, this.bgColor = null, this.radius = null, this.component = null, this.canvas = null, this.canvasInfo = null, this.ctx = null, this.dpr = null, this.rootWidth = null, this.fontFamily = "sans-serif", this.startTime = null, this.$listener = {}
    }
    return _createClass(t, [{
      key: "canvasSize",
      get: function () {
        return {
          width: this.canvas.width / SYS_INFO.screenWidth / this.dpr * this.rootWidth,
          height: this.canvas.height / SYS_INFO.screenWidth / this.dpr * this.rootWidth
        }
      }
    }, {
      key: "queryCanvas",
      value: function () {
        var n = this;
        return new Promise(function (e, r) {
          (n.component || wx).createSelectorQuery().select(n.query).fields({
            node: !0,
            size: !0
          }).exec(function (t) {
            t[0] ? e(t) : (n.debugLogout("找不到画布", "error"), r(t))
          })
        })
      }
    }, {
      key: "create",
      value: function (t) {
        var a = this;
        return new Promise(function (i, e) {
          var o = _objectSpread({
            query: "",
            rootWidth: 375
          }, t);
          o.query || e(new Error("[WxCanvas2d] 'query' is empty.")), a.query = o.query, a.bgColor = o.bgColor, a.component = o.component, a.radius = o.radius, a.queryCanvas().then(function (t) {
            var e = t[0].node,
              r = e.getContext("2d"),
              n = SYS_INFO.pixelRatio;
            a.canvas = e, a.canvasInfo = t, a.ctx = r, a.dpr = n, a.rootWidth = o.rootWidth, a.canvas.width = t[0].width * a.dpr, a.canvas.height = t[0].height * a.dpr, i()
          }).catch(function (t) {
            e(t)
          })
        })
      }
    }, {
      key: "clear",
      value: function () {
        var t, e, r = [0, 0, this.xDpr(this.canvasSize.width), this.xDpr(this.canvasSize.height)];
        ((t = this.ctx).clearRect.apply(t, r), this.radius && (this.drawRectPath({
          x: 0,
          y: 0,
          width: this.canvasSize.width,
          height: this.canvasSize.height,
          radius: this.radius
        }), this.ctx.clip()), this.bgColor) && (this.ctx.fillStyle = this.bgColor, (e = this.ctx).fillRect.apply(e, r))
      }
    }, {
      key: "xDpr",
      value: function (t) {
        return t * this.dpr * SYS_INFO.screenWidth / this.rootWidth
      }
    }, {
      key: "draw",
      value: function (t) {
        var l = this;
        return new Promise(function (c, u) {
          l.startTime = Date.now();
          var e = t.series;
          l.queryCanvas().then(function (t) {
            l.canvas.width = t[0].width * l.dpr, l.canvas.height = t[0].height * l.dpr, l.clear();
            var s = e.map(function (t) {
              return _objectSpread(_objectSpread({}, t), {}, {
                zIndex: t.zIndex || 0
              })
            }).sort(function (t, e) {
              return t.zIndex - e.zIndex
            });
            l.debugLogout("开始绘制"),
              function t() {
                var e = 0 < arguments.length && void 0 !== arguments[0] ? arguments[0] : 0,
                  r = Date.now(),
                  n = s[e];
                if (l.ctx.save(), e < s.length) {
                  var i = n.type,
                    o = (i = void 0 === i ? {} : i).name,
                    a = i.handler;
                  o && "function" == typeof a ? (l.emit("beforeDraw", {
                    index: e,
                    config: n
                  }), a.call(l, n).then(function () {
                    l.debugLogout("绘制成功 - ".concat(o, " [").concat(e + 1, "/").concat(s.length, "] (").concat(Date.now() - r, "ms)")), l.emit("afterDraw", {
                      index: e,
                      config: n
                    }), t(++e)
                  }).catch(function (t) {
                    l.debugLogout("绘制失败"), l.emit("afterDraw", {
                      index: e,
                      config: n,
                      error: t
                    }), u(t)
                  })) : (l.debugLogout("未知类型", "error"), t(++e))
                } else l.debugLogout("绘制完成 (".concat(Date.now() - l.startTime, "ms)")), c();
                l.ctx.restore()
              }()
          }).catch(function (t) {
            u(t)
          })
        })
      }
    }, {
      key: "drawRectPath",
      value: function (t) {
        var n = this,
          e = t.x,
          r = void 0 === e ? 0 : e,
          i = t.y,
          o = void 0 === i ? 0 : i,
          a = t.width,
          s = void 0 === a ? 0 : a,
          c = t.height,
          u = void 0 === c ? 0 : c,
          l = t.radius,
          h = void 0 === l ? 0 : l,
          d = {
            top: 1.5 * Math.PI,
            right: 0,
            bottom: .5 * Math.PI,
            left: Math.PI
          },
          f = [
            [d.left, d.top],
            [d.top, d.right],
            [d.right, d.bottom],
            [d.bottom, d.left]
          ],
          p = [
            [r + h, o + h].map(function (t) {
              return n.xDpr(t)
            }), [r + s - h, o + h].map(function (t) {
              return n.xDpr(t)
            }), [r + s - h, o + u - h].map(function (t) {
              return n.xDpr(t)
            }), [r + h, o + u - h].map(function (t) {
              return n.xDpr(t)
            })
          ];
        this.ctx.beginPath(), Array(4).fill().forEach(function (t, e) {
          var r;
          (r = n.ctx).arc.apply(r, _toConsumableArray(p[e]).concat([n.xDpr(h)], _toConsumableArray(f[e])))
        }), this.ctx.closePath()
      }
    }, {
      key: "setLineStyle",
      value: function () {
        var e = this,
          t = 0 < arguments.length && void 0 !== arguments[0] ? arguments[0] : {},
          r = t.cap,
          n = void 0 === r ? "butt" : r,
          i = t.join,
          o = void 0 === i ? "bevel" : i,
          a = t.offset,
          s = void 0 === a ? 0 : a,
          c = t.dash,
          u = void 0 === c ? [1, 0] : c,
          l = t.color,
          h = void 0 === l ? "#000" : l,
          d = t.width,
          f = void 0 === d ? 2 : d;
        this.ctx.lineCap = n, this.ctx.setLineDash(u.map(function (t) {
          return e.xDpr(t)
        })), this.ctx.lineDashOffset = this.xDpr(s), this.ctx.lineJoin = o, this.ctx.lineWidth = this.xDpr(f), this.ctx.strokeStyle = h
      }
    }, {
      key: "debugLogout",
      value: function () {}
    }, {
      key: "on",
      value: function (t, e) {
        this.$listener[t] ? this.$listener[t].includes(e) || this.$listener[t].push(e) : this.$listener[t] = [e]
      }
    }, {
      key: "off",
      value: function (r, n) {
        var i = this,
          t = this.$listener[r];
        t && (n ? t.some(function (t, e) {
          return t === n && delete i.$listener[r][e]
        }) : delete this.$listener[r])
      }
    }, {
      key: "emit",
      value: function (e, r) {
        Array.isArray(this.$listener[e]) && this.$listener[e].forEach(function (t) {
          return t(_objectSpread({
            event: e
          }, r))
        })
      }
    }]), t
  }();
WxCanvas2d.use = function () {
  var i = 0 < arguments.length && void 0 !== arguments[0] ? arguments[0] : {};
  i.name && i.handler && (WxCanvas2d.prototype[i.name] = function () {
    for (var t, e = arguments.length, r = new Array(e), n = 0; n < e; n++) r[n] = arguments[n];
    return (t = i.handler).call.apply(t, [this].concat(r))
  })
}, module.exports = WxCanvas2d;